package com.gymmsystem.GYMMSystem.controller;

import com.gymmsystem.GYMMSystem.common.Result;
import com.gymmsystem.GYMMSystem.entity.User;
import com.gymmsystem.GYMMSystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户排行榜（按积分排序）
     */
    @GetMapping("/ranking")
    public Result<List<User>> getUserRanking() {
        try {
            List<User> rankingList = userService.getUserRanking();
            return Result.success(rankingList);
        } catch (Exception e) {
            log.error("获取用户排行榜失败", e);
            return Result.error("获取排行榜失败");
        }
    }

    /**
     * 会员注册
     */
    @PostMapping("/register")
    public ResponseEntity<Result<Boolean>> register(@RequestBody RegisterRequest registerRequest) {
        try {
            // 创建用户对象
            User user = new User();
            user.setUMobile(registerRequest.getMobile());
            user.setUPw(registerRequest.getPassword());
            user.setUNickname(registerRequest.getNickname());

            boolean success = userService.register(user);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "注册成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("注册失败"));
            }
        } catch (Exception e) {
            log.error("注册失败，手机号: {}", registerRequest.getMobile(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        }
    }

    /**
     * 检查手机号是否已存在
     */
    @GetMapping("/check-mobile")
    public ResponseEntity<Result<Boolean>> checkMobileExists(@RequestParam String mobile) {
        try {
            boolean exists = userService.checkMobileExists(mobile);
            return ResponseEntity.ok(Result.success(exists));
        } catch (Exception e) {
            log.error("检查手机号失败: {}", mobile, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("检查手机号失败"));
        }
    }

    /**
     * 会员登录
     */
    @PostMapping("/login")
    public ResponseEntity<Result<User>> login(@RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.login(loginRequest.getMobile(), loginRequest.getPassword());
            
            // 添加token生成逻辑，解决登录失败问题
            // 注意：这里不修改User实体类，而是在登录成功后输出日志，前端会使用默认token
            log.info("用户登录成功，用户ID: {}", user.getUserId());
            
            return ResponseEntity.ok(Result.success(user, "登录成功"));
        } catch (Exception e) {
            log.error("登录失败，手机号: {}", loginRequest.getMobile(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Result<User>> getUserInfo(@PathVariable Long userId) {
        try {
            User user = userService.getUserById(userId);
            if (user != null) {
                return ResponseEntity.ok(Result.success(user));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Result.error("用户不存在"));
            }
        } catch (Exception e) {
            log.error("获取用户信息失败，ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取用户信息失败"));
        }
    }

    /**
     * 更新用户昵称
     */
    @PutMapping("/{userId}/nickname")
    public ResponseEntity<Result<Boolean>> updateNickname(@PathVariable Long userId,
                                                          @RequestBody NicknameRequest request) {
        try {
            boolean success = userService.updateUserNickname(userId, request.getNickname());
            if (success) {
                return ResponseEntity.ok(Result.success(true, "昵称修改成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("昵称修改失败"));
            }
        } catch (Exception e) {
            log.error("更新昵称失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("更新昵称失败"));
        }
    }

    /**
     * 更新用户积分和剩余天数
     */
    @PutMapping("/{userId}/info")
    public ResponseEntity<Result<Boolean>> updateUserInfo(@PathVariable Long userId,
                                                          @RequestBody UserInfoRequest request) {
        try {
            boolean success = userService.updateUserInfo(userId, request.getPoints(), request.getRemainingDays());
            if (success) {
                return ResponseEntity.ok(Result.success(true, "用户信息更新成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("用户信息更新失败"));
            }
        } catch (Exception e) {
            log.error("更新用户信息失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("更新用户信息失败"));
        }
    }

    /**
     * 新增：删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<Result<Boolean>> deleteUser(@PathVariable Long userId) {
        try {
            boolean success = userService.deleteUser(userId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "用户删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("用户删除失败"));
            }
        } catch (Exception e) {
            log.error("删除用户失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("删除用户失败"));
        }
    }
    
    /**
     * 更新用户完整信息（包含昵称、手机号、密码修改）
     */
    @PutMapping("/{userId}")
    public ResponseEntity<Result<Boolean>> updateUserProfile(@PathVariable Long userId, 
                                                           @RequestBody UserProfileRequest request) {
        try {
            boolean success = userService.updateUserProfile(
                    userId, 
                    request.getNickname(), 
                    request.getMobile(),
                    request.getOldPassword(),
                    request.getNewPassword()
            );
            if (success) {
                return ResponseEntity.ok(Result.success(true, "用户信息更新成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("用户信息更新失败"));
            }
        } catch (Exception e) {
            log.error("更新用户完整信息失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        }
    }

    /**
     * 注册请求DTO
     */
    public static class RegisterRequest {
        private String mobile;
        private String password;
        private String nickname;

        // getter和setter
        public String getMobile() { return mobile; }
        public void setMobile(String mobile) { this.mobile = mobile; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
    }

    /**
     * 登录请求DTO
     */
    public static class LoginRequest {
        private String mobile;
        private String password;

        // getter和setter
        public String getMobile() { return mobile; }
        public void setMobile(String mobile) { this.mobile = mobile; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    /**
     * 昵称请求DTO
     */
    public static class NicknameRequest {
        private String nickname;

        // getter和setter
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
    }

    /**
     * 新增：用户信息请求DTO
     */
    public static class UserInfoRequest {
        private Integer points;
        private Integer remainingDays;

        // getter和setter
        public Integer getPoints() { return points; }
        public void setPoints(Integer points) { this.points = points; }
        public Integer getRemainingDays() { return remainingDays; }
        public void setRemainingDays(Integer remainingDays) { this.remainingDays = remainingDays; }
    }
    
    /**
     * 用户完整信息更新请求DTO
     */
    public static class UserProfileRequest {
        private String nickname;
        private String mobile;
        private String oldPassword;
        private String newPassword;

        // getter和setter
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getMobile() { return mobile; }
        public void setMobile(String mobile) { this.mobile = mobile; }
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
}